from src import listen_unicast,join_multicast_group
from src import balancer
import time
from src import device_heartbeat,Node_raw_data,Device_config
from epics import caput

Node_pvname_data = {}
for pvname,host in Node_raw_data.items():
     Node_pvname_data[host] = pvname
def heartbeat_monitor():
    time.sleep(3)
    print("UDP心跳监听线程已启动")
    while True:
        time.sleep(3)
        try:
            for host,num in device_heartbeat.heartbeat_num.items():
                if num > 2:
                    a = caput(Device_config["心跳状态"].format(Node_pvname_data[host]),1)
                else:
                    a = caput(Device_config["心跳状态"].format(Node_pvname_data[host]),0)
            device_heartbeat.clear_heartbeat()

            for host,ready in device_heartbeat.ready.items():
                a = caput(Device_config["心跳状态_Ready"].format(Node_pvname_data[host]),ready)
        except KeyboardInterrupt as e:
            print("UDP心跳监听线程已退出")
            break
             
def Unicast_group():
    time.sleep(3)
    sockuni=listen_unicast()
    print("UDP单播监听线程已启动")
    while True:
        try:
            time.sleep(0.01)
            data, addr = sockuni.recvfrom(1024)
            # print(f"Received data unicast from {addr}: {data.hex()}")
            balancer.send_message({"from":"UDP","host":addr[0],"data":data})
        except KeyboardInterrupt as e:
            print("UDP单播监听线程已退出")
            break
def Multicast_group():
    time.sleep(3)
    sockmulti=join_multicast_group()
    print("UDP组播监听线程已启动")
    while True:
        try:
            time.sleep(0.01)
            data, addr = sockmulti.recvfrom(1024)
            # print(f"Received data multi from {addr}: {data.hex()}")
            balancer.send_message({"from":"UDP","host":addr[0],"data":data})
        except KeyboardInterrupt as e:
            print("UDP组播监听线程已退出")
            break
